let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')
const utils = require('../utils/utils.js')


// 查询 maoyuan  keyword检索
router.get('/list', async function (req, res, next) {
    let result = {}
    try {
        let page = utils.getQueryValue(req.query.page)
        let pageSize = utils.getQueryValue(req.query.pageSize)
        let sqlLimit = " limit " + (page - 1) * pageSize + ", " + pageSize
        sqlLimit = ((sqlLimit.indexOf('NaN')>-1 || sqlLimit.indexOf("undefined")>-1 || pageSize=='' || page=='') ? "" : sqlLimit)
        let keyword = utils.getQueryValue(req.query.keyword)
        let dept = utils.getQueryValue(req.query.dept)
        dept = Array.isArray(dept) ? dept[dept.length - 1] : dept
        let TransmitterNumber = utils.getQueryValue(req.query.TransmitterNumber)
        let AnntenaNumber = utils.getQueryValue(req.query.AnntenaNumber)
        let Frequency = utils.getQueryValue(req.query.Frequency)
        let Capacity = utils.getQueryValue(req.query.Capacity)
        let filerData = JSON.parse(utils.getQueryValue(req.query.filterData))
        let AlertType = utils.getQueryValue(filerData.AlertType)
        let status = utils.getQueryValue(filerData.status)
        let startTime = utils.getQueryValue(req.query.startTime)
        let endTime = utils.getQueryValue(req.query.endTime)

        let sqlWhere = " WHERE 1=1"
        sqlWhere += (keyword!='' ? " and (AlertContent like '%" + keyword + "%' or DataSnapshot like '%" + keyword + "%') " : "")
        sqlWhere += ((AlertType=='' || AlertType=='-1')? "" : " and AlertType in ("+AlertType+")")
        sqlWhere += ((dept=='' || dept=='-1')? "" : " and SationID="+dept+"")
        sqlWhere += ((status== '' || status=="-1")? "" : " and status in ("+status+")")
        sqlWhere += (TransmitterNumber != '' ? " and TransmitterNumber="+TransmitterNumber+"" : "")
        sqlWhere += (AnntenaNumber != '' ? " and AnntenaNumber="+AnntenaNumber+"" : "")
        sqlWhere += (Frequency != '' ? " and Frequency="+Frequency+"" : "")
        sqlWhere += (Capacity != '' ? " and Capacity="+Capacity+"" : "")        
        sqlWhere += (startTime != '' ? " and time>='"+startTime+"'" : "")
        sqlWhere += (endTime != '' ? " and time<='"+endTime+"'" : "")

        total = (await mysqlHelper.query("select count(1) as ct from scheme_alert u " + sqlWhere))[0].ct
        let prop = utils.getQueryValue(req.query.prop)
        let order = utils.getQueryValue(req.query.order)
        // if (order=='ascending')
        //     order="ASC"
        // else if (order=='descending')
        //     order='DESC'
        order = (order=='ascending'? 'ASC': 'DESC')
        let sqlOrder = " ORDER by " + prop+" "+ order
        sqlOrder = ((prop.indexOf('NaN')>-1 || order.indexOf("undefined")>-1 || prop=='' || order=='') ? "" : sqlOrder)

        let sqlStr = "select * from (    \
                        SELECT a.*,d1.label typelabel,d2.label statuslabel,b.StationName,getParentList(b.StationId) as fullorgName, \
                                tr.trackID,tr.tracker,tr.tracktime,tr.trackcontent,tr.transactionType,d3.label transactionTypelabel \
                        FROM scheme_alert a   \
                        left join (select * from sys_dict_detail where dict_id=(select id from sys_dict where code='AlertType' )) d1 on a.AlertType=d1.value  \
                        left join (select * from sys_dict_detail where dict_id=(select id from sys_dict where code='AlertStatus' )) d2 on a.status=d2.value  \
                        left join base_station b on a.StationID=b.StationId  \
                        left join scheme_alert_track tr on a.AlertID=tr.AlertID \
                        left join (select * from sys_dict_detail where dict_id=(select id from sys_dict where code='AlertTransactionType' )) d3 on tr.transactionType=d3.value  \
                      ) raw "
        sqlStr += sqlWhere + sqlOrder + sqlLimit 
        rows = await mysqlHelper.query(sqlStr)
        rows.forEach((user, index, arr) => {
            user.group = (user.group ? user.group.split(',') : [])
        })
        result.code = 200
        result.data = {
            'total': total,
            'page': page,
            'pageSize': pageSize,
            'summary': {
                'id': page * pageSize,
                'name': '999'
            },
            rows: rows
        }
        result.message = ''
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 预警报警处置
router.post('/track', async function (req, res, next) {
    let result = {}
    try {
        let sqlStr = ""
        let id = utils.getQueryValue(req.body.trackID)
        let alertID = utils.getQueryValue(req.body.alertID)
        let transactionType = utils.getQueryValue(req.body.transactionType)
        let workflowID = utils.getQueryValue(req.body.workflowID)
        let tracker = utils.getQueryValue(req.body.tracker)
        let tracktime = utils.getQueryValue(req.body.tracktime)
        let trackcontent = utils.getQueryValue(req.body.trackcontent)
        if (id == '') { //新增
            sqlStr = "insert into scheme_alert_track(alertID,transactionType,workflowID,tracker,tracktime,trackcontent) values (" + alertID + "," + transactionType + ",'" + workflowID + "'," + tracker+ ",'" + tracktime + "','" + trackcontent+"')"
            await mysqlHelper.query(sqlStr)
        } else { //修改
            let deptStr = Array.isArray(req.body.dept) ? req.body.dept[req.body.dept.length - 1] : req.body.dept
            //let sexStr = utils.getQueryValue(req.body.sex) == '' ? "" : ",sex=" + req.body.sex
            sqlStr = "UPDATE scheme_alert_track SET transactionType=" + transactionType + ",workflowID='"+workflowID+"',tracker=" +tracker + ",tracktime='" + tracktime + "',trackcontent='" + trackcontent + "' WHERE trackID=" + id
            await mysqlHelper.query(sqlStr)
        }
        result.code = 200
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)  
})

module.exports = router

